package com.pp.pingpong;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.StrictMode;
import android.util.Log;


public class ConnectionManager  extends AsyncTask<Void, Void, Void>{
	
	Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null; 
    
    String ip;
    int port;
    
    public Boolean connected = false;
    
    public ConnectionManager(String ip, int port){
    	
    	this.ip = ip;
    	this.port = port;
    	
    }
    
    public Boolean makeConnection(){     	
				
		InetAddress serverAddr = null;
		try {
			serverAddr = InetAddress.getByName(ip);
		} catch (UnknownHostException e1) {			
			e1.printStackTrace();
		}
		try {
			Log.d("Socket", "Creating socket");
			socket = new Socket(serverAddr, port);
			Log.d("Socket", "Socket created");
		} catch (IOException e) {		
			e.printStackTrace();
		}  							
		if (socket!=null){
			return socket.isConnected();
		}
		else
			return false;
    }
    
    public void send(String message) {
    	
    	try {
			out = new PrintWriter(socket.getOutputStream(), true);
		} catch (IOException e) {		
			e.printStackTrace();
		}
    	
    	out.println(message);
    	
	
    }
    
    public String recived() {

    	String message = "";
    	
    	try {
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		} catch (IOException e) {		
			e.printStackTrace();
		}   
    	

		try {
			while ((in.readLine()) != null) {	
				message += in.readLine();
				System.out.println( in.readLine());
			}
		} catch (IOException e) {			
			e.printStackTrace();
		}
		
		return message;
    }

	@Override
	protected Void doInBackground(Void... arg0) {
		makeConnection();
		return null;
	}
    
       
      
    




    
}
